from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

# 生成 RSA 密钥对
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

# 将密钥保存到文件
with open('private_key.pem', 'wb') as f:
    f.write(private_key)

with open('public_key.pem', 'wb') as f:
    f.write(public_key)

# 要加密的数据
data_to_encrypt = b'This is a secret message.'

# 使用公钥加密
recipient_key = RSA.import_key(open('public_key.pem').read())
cipher_rsa = PKCS1_OAEP.new(recipient_key)
encrypted_data = cipher_rsa.encrypt(data_to_encrypt)

# 将加密后的数据进行 Base64 编码以便显示
encoded_encrypted_data = base64.b64encode(encrypted_data).decode()
print(f'加密后的内容：{encoded_encrypted_data}')

# 使用私钥解密
private_key = RSA.import_key(open('private_key.pem').read())
cipher_rsa = PKCS1_OAEP.new(private_key)
decrypted_data = cipher_rsa.decrypt(encrypted_data)

print(f'解密后的内容：{decrypted_data.decode()}')